"""文件操作"""

from typing import Optional
from pydantic import Field
from mcp.server import FastMCP
import docker
import subprocess
from .container import get_container


def add_file_tools(mcp: FastMCP, _docker: docker.DockerClient):

    @mcp.tool()
    async def list_container_files(
            name: str = Field(default="python-sandbox", description="容器名称."),
            container_id: Optional[str] = Field(default=None, description="容器id."),
            file_dir: str = Field(default='/files', description="容器的文件路径.")
    ):
        """显示沙箱的文件列表"""
        container = get_container(_docker, name, container_id)
        if container is None:
            return {'success': False, 'message': '未找到相应的容器.'}
        command = f"docker exec -i {container.short_id} ls -al {file_dir}"
        result = subprocess.run(command, shell=True, capture_output=True)
        if result.returncode == 0:
            return {'success': True, 'message': result.stdout}
        else:
            return {'success': False, 'message': result.stderr.decode()}

    @mcp.tool()
    async def make_dir_in_container(
            name: str = Field(default="python-sandbox", description="容器名称."),
            container_id: Optional[str] = Field(default=None, description="容器id."),
            target_dir: str = Field(default=..., description="待创建的目录."),
    ):
        """在容器中创建目录"""
        container = get_container(_docker, name, container_id)
        if container is None:
            return {'success': False, 'message': '未找到相应的容器.'}
        command = f"docker exec -i {container.short_id} mkdir -p {target_dir}"
        result = subprocess.run(command, shell=True, capture_output=True)
        if result.returncode == 0:
            return {'success': True, 'message': result.stdout}
        else:
            return {'success': False, 'message': result.stderr.decode()}

    @mcp.tool()
    async def upload_file_to_container(
            name: str = Field(default="python-sandbox", description="容器名称."),
            container_id: Optional[str] = Field(default=None, description="容器id."),
            local_file: str = Field(default=..., description="本地文件路径."),
            container_path: str = Field(default='/files', description="容器文件路径.")
    ):
        """上传本地文件到容器"""
        container = get_container(_docker, name, container_id)
        if container is None:
            return {'success': False, 'message': '未找到相应的容器.'}
        command = f"docker cp {local_file} {container.short_id}:{container_path}"
        result = subprocess.run(command, shell=True, capture_output=True)
        if result.returncode == 0:
            return {'success': True, 'message': result.stdout}
        else:
            return {'success': False, 'message': result.stderr.decode()}

    @mcp.tool()
    async def download_file_from_container(
            name: str = Field(default="python-sandbox", description="容器名称."),
            container_id: Optional[str] = Field(default=None, description="容器id."),
            container_file: str = Field(default=..., description="容器文件路径."),
            local_path: str = Field(default='./', description="本地文件路径.")
    ):
        """将容器文件拷贝到本地"""
        container = get_container(_docker, name, container_id)
        if container is None:
            return {'success': False, 'message': '未找到相应的容器.'}
        command = f"docker cp {container.short_id}:{container_file} {local_path}"
        result = subprocess.run(command, shell=True, capture_output=True)
        if result.returncode == 0:
            return {'success': True, 'message': result.stdout}
        else:
            return {'success': False, 'message': result.stderr.decode()}
